<template>

    <el-tabs v-model="activeTab" @tab-click="handleClick">
        <el-tab-pane label="收件箱" name="outboxTab">
            <!-- 在此处添加收件箱的内容 -->
            <div class="tab-content">
                <el-table :data="inboundMails" style="width: 1200px">
                    <el-table-column prop="sender" label="发送人" width="160"> </el-table-column>
                    <el-table-column prop="recipient" label="接收人" width="160"> </el-table-column>
                    <el-table-column prop="subject" label="主题" width="120"> </el-table-column>
                    <el-table-column prop="content" label="内容"> </el-table-column>
                    <el-table-column prop="send_date" label="发送日期" width="200" :formatter="dateFormatter"> </el-table-column>
                </el-table>
            </div>
        </el-tab-pane>
        <el-tab-pane label="发件箱" name="inboxTab">
            <div class="tab-content">
                <el-table :data="outboundMails" style="width: 1200px">
                    <el-table-column prop="sender" label="发送人" width="160"> </el-table-column>
                    <el-table-column prop="recipient" label="接收人" width="160"> </el-table-column>
                    <el-table-column prop="subject" label="主题" width="120"> </el-table-column>
                    <el-table-column prop="content" label="内容"> </el-table-column>
                    <el-table-column prop="send_date" label="发送日期" width="200"  :formatter="dateFormatter"> </el-table-column>
                </el-table>
            </div>
        </el-tab-pane>
    </el-tabs>

    <router-link to="/config">
        <el-button type="primary">账号配置</el-button>
    </router-link>
    <el-select v-model="selected" placeholder="选择账号" style="width: 240px">
        <el-option v-for="item in accounts" :key="item.id" :label="item.email_account" :value="item.id">
        </el-option>
    </el-select>
    <el-button type="primary" @click="requireNew()">收信</el-button>
    <el-button type="primary" @click="createMail()">写信</el-button>

    <el-dialog v-model="dialogVisible" title="写信" width="100%">
        <el-form ref="mailFormRef" :model="mailForm" :rules="rules" label-width="80px">
            <el-form-item label="收件人" prop="recipient">
                <el-input v-model="mailForm.recipient"></el-input>
            </el-form-item>
            <el-form-item label="邮件主题" prop="subject">
                <el-input v-model="mailForm.subject"></el-input>
            </el-form-item>
            <el-form-item label="邮件正文" prop="body">
                <el-input type="textarea" v-model="mailForm.body" :autosize="{ minRows: 20, maxRows: 20 }"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="resetForm(mailFormRef)">重置</el-button>
            <el-button type="primary" :loading="sending" @click="sendMail(mailFormRef)">发送</el-button>
        </div>
    </el-dialog>

</template>
<style scoped>
.tab-content {
    min-height: 400px;
}
</style>
<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const dateFormatter = (row: any) => {
    const userLocale = navigator.language;
    return new Date(row.send_date).toLocaleString(userLocale);
}

const activeTab = ref('inboxTab'); // 设置默认标签页为收件箱
const handleClick = (tab) => {
    console.log(tab.value);
};
const outboundMails = ref([]);
const getOutbox = async () => {
    const response = await fetch("/api/mail-center/outbox", {
        method: "GET",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            'Authorization': 'Bearer ' + sessionStorage.getItem('x-token'),
        }
    });
    outboundMails.value = await response.json();
};
const inboundMails = ref([]);
const getInbox = async () => {
    const response = await fetch("/api/mail-center/inbox", {
        method: "GET",
        headers: {
            "Content-Type": "application/json",
            'Authorization': 'Bearer ' + sessionStorage.getItem('x-token')
        }
    });
    inboundMails.value = await response.json();
};
const { appContext } = getCurrentInstance();
const accounts = ref([]);
const selected = ref(null);
const dialogVisible = ref(false);

const requireNew = async () => {
    const response = await fetch("/api/mail-center/receive", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            'Authorization': 'Bearer ' + sessionStorage.getItem('x-token')
        },
        body: JSON.stringify({
            accountId: selected.value
        })
    });
    const data = await response.json();
    ElMessageBox({
        message: data.message,
        type: 'success',
    })
}
const getConfig = () => {
    fetch('/api/mail-account', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + sessionStorage.getItem('x-token')
        }
    })
        .then(response => response.json())
        .then(data => {
            accounts.value = data;
            if (data.length > 0) {
                selected.value = data[0].id
            }
        })
        .catch(error => {
            console.error('Error getting accounts:', error);
        });
};

const createMail = () => {
    console.log('create mail')
    dialogVisible.value = true;
};


const sending = ref(false);
interface MailForm {
    recipient: string
    subject: string
    body: string
}

const mailForm = reactive<MailForm>({
    recipient: '',
    subject: '',
    body: ''
})


const mailFormRef = ref<FormInstance>()



const rules = reactive<FormRules<MailForm>>({
    recipient: [
        { required: true, message: '请输入收件人邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱', trigger: ['blur', 'change'] },
    ],
    subject: [
        {
            required: true,
            message: '请输入邮件主题',
            trigger: 'blur',
        },
    ],
    body: [
        {
            required: true,
            message: '请输入邮件正文',
            trigger: 'change',
        },
    ]
})


const sendMail = async (formEl: FormInstance | undefined) => {
    /**
     * TODO: 
     * 1. 封装一下fetch 统一加上Bearer Token, 统一异常处理
     */
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            sending.value = true;
            fetch('/api/mail-center/send', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + sessionStorage.getItem('x-token')
                },
                body: JSON.stringify({
                    ...mailForm,
                    account_id: selected.value
                })
            })
                .then(response => response.json())
                .then(data => {

                    if (data.code === 200) {
                        ElMessage({
                            message: '发送成功',
                            type: 'success',
                        })
                        dialogVisible.value = false;
                    } else {
                        ElMessageBox.alert(data.message, '发送失败', {}, appContext)
                    }

                })
                .catch(error => {
                    ElMessageBox({
                        message: error.message,
                        type: 'error',
                    })
                    console.error('Error sending mail:', error);
                }).finally(() => {
                    sending.value = false;
                })

        }
    })




};

const resetForm = (formEl: FormInstance | undefined) => {
    console.log(formEl)
    if (!formEl) return
    formEl.resetFields()
}

onMounted(() => {
    getConfig();
    getOutbox();
    getInbox();
});




</script>
